package com.monitor.service.monitor;

import com.monitor.model.MonitorConfig;
import com.monitor.model.ServerConfig;
import com.monitor.model.ServerStatus;
import com.monitor.util.SSHClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 抽象服务器监控类
 * 模板方法模式：定义监控流程的骨架
 */
public abstract class AbstractServerMonitor implements IServerMonitor {
    protected static final Logger logger = LoggerFactory.getLogger(AbstractServerMonitor.class);
    
    protected final ServerConfig serverConfig;
    protected final MonitorConfig monitorConfig;
    
    /**
     * 构造函数
     * @param serverConfig 服务器配置
     * @param monitorConfig 监控配置
     */
    public AbstractServerMonitor(ServerConfig serverConfig, MonitorConfig monitorConfig) {
        this.serverConfig = serverConfig;
        this.monitorConfig = monitorConfig;
    }
    
    @Override
    public ServerConfig getServerConfig() {
        return serverConfig;
    }
    
    /**
     * 模板方法：定义监控的基本流程
     */
    @Override
    public ServerStatus checkServerHealth() {
        ServerStatus status = new ServerStatus(serverConfig);
        SSHClient sshClient = createSSHClient();
        
        try {
            boolean connected = connectToServer(sshClient);
            
            if (connected) {
                status.setOnline(true);
                collectServerMetrics(sshClient, status);
            } else {
                handleConnectionFailure(status);
            }
        } catch (Exception e) {
            handleMonitoringError(status, e);
        } finally {
            disconnectSSHClient(sshClient);
        }
        
        return status;
    }
    
    /**
     * 创建SSH客户端
     * @return SSH客户端实例
     */
    protected SSHClient createSSHClient() {
        return new SSHClient(
            monitorConfig.getConnectionTimeout(), 
            monitorConfig.getCommandTimeout()
        );
    }
    
    /**
     * 连接到服务器
     * @param sshClient SSH客户端
     * @return 连接是否成功
     */
    protected boolean connectToServer(SSHClient sshClient) {
        if ("PASSWORD".equalsIgnoreCase(serverConfig.getAuthType())) {
            return sshClient.connect(
                serverConfig.getHost(),
                serverConfig.getPort(),
                serverConfig.getUsername(),
                serverConfig.getPassword()
            );
        } else if ("KEY".equalsIgnoreCase(serverConfig.getAuthType())) {
            return sshClient.connectWithKey(
                serverConfig.getHost(),
                serverConfig.getPort(),
                serverConfig.getUsername(),
                serverConfig.getPrivateKeyPath()
            );
        }
        return false;
    }
    
    /**
     * 收集服务器指标
     * 交给子类实现具体的指标收集逻辑
     * @param sshClient SSH客户端
     * @param status 服务器状态
     */
    protected abstract void collectServerMetrics(SSHClient sshClient, ServerStatus status);
    
    /**
     * 处理连接失败情况
     * @param status 服务器状态
     */
    protected void handleConnectionFailure(ServerStatus status) {
        status.setOnline(false);
        status.setErrorMessage("无法连接到服务器");
        logger.warn("无法连接到服务器: {}", serverConfig.getHost());
    }
    
    /**
     * 处理监控过程中的错误
     * @param status 服务器状态
     * @param e 异常
     */
    protected void handleMonitoringError(ServerStatus status, Exception e) {
        logger.error("监控服务器失败: {}", e.getMessage());
        status.setOnline(false);
        status.setErrorMessage("监控过程出错: " + e.getMessage());
    }
    
    /**
     * 断开SSH连接
     * @param sshClient SSH客户端
     */
    protected void disconnectSSHClient(SSHClient sshClient) {
        if (sshClient != null) {
            sshClient.disconnect();
        }
    }
} 